<!DOCTYPE html>
<html>
<head>
    <title>Canvas Translate Rectangle</title>
</head>
<body>
    <canvas id="myCanvas" width="400" height="400" style="border:1px solid #000000;"></canvas>
    <button id="moveButton">rotate Rectangle</button>

    <script>
      let canvas = document.getElementById('myCanvas');
      let ctx = canvas.getContext('2d');

      let x = 150, y = 150, width = 100, height = 50, rotate = 0;
      let moveButton = document.getElementById('moveButton');

      function moveRect() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.save();
        /**
         * 保持中心点不变
         * 1. 先将画布的原点移动到矩形的中心点
         * 2. 旋转画布
         * 3. 将画布的原点移动到矩形的左上角
         * 
         * x + width / 2, y + height / 2: 矩形的中心点坐标
         * rotate: 旋转角度
         * 画布原点的计算公式：(x, y) = (x + width / 2, y + height / 2)
        */
        ctx.translate(x + width / 2, y + height / 2);
        ctx.rotate(rotate * Math.PI / 180);
        ctx.fillRect(-width / 2, -height / 2, width, height);
        ctx.restore();
        rotate += 10;
        if (rotate > 360) {
          rotate = 0;
        }
      }
      moveRect();
      moveButton.addEventListener('click', moveRect)
    </script>
</body>
</html>